package org.spring.springboot.controller;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.spring.springboot.config.avoidRepeatable.AvoidRepeatableCommit;
import org.spring.springboot.config.limit.RequestRateLimitException;
import org.spring.springboot.config.limit.RequestRateLimitUtil;
import org.spring.springboot.config.limit.RequestRateLimiter;
import org.spring.springboot.domain.City;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SessionController {
	//测试分布式session 使用redis缓存
	@AvoidRepeatableCommit
	@RequestMapping("/uid")
	public String uid(HttpServletRequest request) {
		UUID uid = (UUID) request.getSession().getAttribute("uid");
		if (uid == null) {
			uid = UUID.randomUUID();
		}
		request.getSession().setAttribute("uid", uid);
		return request.getSession().getId();
	}
	@RequestRateLimiter
	@RequestMapping("/uidLimiter")
	public String uidLimiter(HttpServletRequest request) throws RequestRateLimitException{
	
		try {
			boolean checkLimit = RequestRateLimitUtil.checkLimit();
			if (checkLimit) {
				return "我被限流了,去做降级吧,比如缓存";
			}
			UUID uid = (UUID) request.getSession().getAttribute("uid");
			if (uid == null) {
				uid = UUID.randomUUID();
			}
			request.getSession().setAttribute("uid", uid);
			return request.getSession().getId();
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}
	

	@RequestRateLimiter()
	@RequestMapping("/cityLimiterCache0")
	public City cityLimiterCache0(@RequestBody City city) throws RequestRateLimitException{
		try {
			return city;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@RequestRateLimiter(cache = 1,cacheKeyName="city",cacheKeyParameter ="provinceId,cityName,description" )
	@RequestMapping("/cityLimiterCache1")
	public City cityLimiterCache1(@RequestBody City city) throws RequestRateLimitException{
		try {
			return city;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
